package com.ddy.test.creditcardmanage

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import com.ddy.test.creditcardmanage.R.id.recordAmount
import com.ddy.test.creditcardmanage.model.CardRecord
import com.ddy.test.creditcardmanage.model.CardViewModel

class AddCardRecord :  AppCompatActivity() {
    companion object {
        private const val LOG_TAG: String = "CCM_ADD_RECORD"

        private const val RECORD_TYPE_SPEND = -1
        private const val RECORD_TYPE_REPAYMENT = 1
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        val inflater = menuInflater
        inflater.inflate(R.menu.add_save, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.add_card_record)

        val cardName = this.intent.getStringExtra("cardName")
        title = "Add Record-$cardName"

        val recordTypeSpend = findViewById<RadioButton>(R.id.recordTypeSpend)
        recordTypeSpend.isChecked = true

        findViewById<EditText>(recordAmount).inputType = EditorInfo.TYPE_CLASS_PHONE
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val cardId = this.intent.getLongExtra("cardId", 0)
        return when (item.itemId) {
            R.id.action_add_save ->{
                val cardViewModel = CardViewModel(this.application)
                val radioGroup = findViewById<RadioGroup>(R.id.recordType)
                val checkedRadioButtonId = radioGroup.checkedRadioButtonId
                val recordType = if(checkedRadioButtonId == R.id.recordTypeSpend){
                    RECORD_TYPE_SPEND
                }else{
                    RECORD_TYPE_REPAYMENT
                }

                val amount: String = findViewById<EditText>(recordAmount).text.toString().trim()
                if(amount.isBlank()){
                    Toast.makeText(this,"请输入金额", Toast.LENGTH_LONG).show()
                }else{
                    val card = cardViewModel.getCard(cardId)
                    card.statementAmount = card.statementAmount + (recordType * amount.toFloat())
                    cardViewModel.addCardRecord(CardRecord.newCardRecord(cardId, recordType, amount.toFloat()))
                    cardViewModel.updateCard(card)
                    finish()
                }
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}
